package com.answer.petsale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.answer.petsale.model.entity.Animal;
import com.answer.petsale.model.entity.Order;
import com.answer.petsale.model.vo.DashboardStatsVO;
import com.answer.petsale.mapper.OrderMapper;
import com.answer.petsale.service.AnimalService;
import com.answer.petsale.service.DashboardService;
import com.answer.petsale.service.OrderService;
import com.answer.petsale.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.YearMonth;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Resource
    private UserService userService;

    @Resource
    private AnimalService animalService;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public DashboardStatsVO getDashboardStats() {
        DashboardStatsVO statsVO = new DashboardStatsVO();

        // 1. 统计总用户数
        long totalUsers = userService.count();
        statsVO.setTotalUsers(totalUsers);

        // 2. 统计在售宠物数
        QueryWrapper<Animal> animalWrapper = new QueryWrapper<>();
        animalWrapper.eq("sale_status", 0); // 0 = 在售
        long petsForSale = animalService.count(animalWrapper);
        statsVO.setPetsForSale(petsForSale);

        // 3. 统计待审批预定数
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("status", 0); // 0 = 待审核
        long pendingOrders = orderService.count(orderWrapper);
        statsVO.setPendingOrders(pendingOrders);

        // 4. 计算本月成交额
        YearMonth currentMonth = YearMonth.now();
        LocalDateTime startTime = currentMonth.atDay(1).atStartOfDay();
        LocalDateTime endTime = currentMonth.atEndOfMonth().plusDays(1).atStartOfDay();
        BigDecimal monthlySales = orderMapper.sumSalesBetweenDates(startTime, endTime);
        // 如果本月没有销售额，结果会是 null，需要处理
        statsVO.setMonthlySales(monthlySales != null ? monthlySales : BigDecimal.ZERO);

        return statsVO;
    }
}